package com.zb.util;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class TokenDecode {
    //公钥
    private static final String PUBLIC_KEY = "public.key";

    private static String publickey="";
    /**
     * 获取非对称加密公钥 Key
     * @return 公钥 Key
     */
    public static String getPubKey() {
        if(!StringUtils.isEmpty(publickey)){
            return publickey;
        }
        Resource resource = new ClassPathResource(PUBLIC_KEY);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(inputStreamReader);
            publickey = br.lines().collect(Collectors.joining("\n"));
            return publickey;
        } catch (IOException ioe) {
            return null;
        }
    }
    /***
     * 读取令牌数据
     */
    public static Map<String,String> dcodeToken(String token){
        //校验Jwt
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(getPubKey()));
        //获取Jwt原始内容
        String claims = jwt.getClaims();
        return JSON.parseObject(claims,Map.class);
    }

    public static void main(String[] args) {
        Map<String, String> stringStringMap = dcodeToken("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhcHAiXSwibmFtZSI6bnVsbCwiaWQiOm51bGwsImV4cCI6MjA5OTk5ODUxMiwiYXV0aG9yaXRpZXMiOlsic2Vja2lsbF9saXN0IiwiZ29vZHNfbGlzdCJdLCJqdGkiOiI1MDQyZDBhNy0zMzY2LTQzMWUtOGYzMy1mYmY4MjlhMGI5OWMiLCJjbGllbnRfaWQiOiJhY2NwIiwidXNlcm5hbWUiOiJ4aW5nemhlIn0.KZ950FhfIBxt5huTsnnysm_60J7tu8Vk6k8dIPG_cQn_dosL_C9j1LZQ8hcFTBEsVqLoNdQRdE6qcNQIjaPTnOr8jk7GhfMPSCpLjsZ8JYPOLmKBLhFBahNIpsBrX4UbtdD_IzD8pbGsB4SVXrpL1nD0rD0bycH1U0Y_2lGaPQBsgUUerZFnEh4SIYv1Q7Dz6DI9QjKeboj2kxx_kmDHj0X1zEjvChq-a1o1XRVYFGLfElSPNCo9W93Qym7M0F0HV4L790qmo8ibphXJeQ74NDRcsYzDvLPx489xVBucRUVvnqZPsugknG3bYTkPwSiA8xdWMeGMTgR0uCpjUhYQTg");
        System.out.println(stringStringMap.get("username"));

    }
    /***
     * 获取用户信息
     * @return
     */
    public static Map<String,String> getUserInfo(){
        //获取授权信息
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        //令牌解码
        return dcodeToken(details.getTokenValue());
    }
}
